package utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * Mybatis 工具
 *
 * @author 修唯xiuwei
 * @Email 524710549@qq.com
 **/
@Slf4j
public class MybatisUtils {

	private static Reader reader = null;

	public static SqlSessionFactory factory = null;

	public static SqlSessionFactoryBuilder builder;


	private static Reader getReader() {
		if (reader == null) {
			try {
				reader = Resources.getResourceAsReader("mybatisconfig.xml");
			} catch (IOException e) {
				log.error("读取Mybatis配置文件失败");
			}
		}
		return reader;
	}


	public static SqlSession getSqlSession() {
		return getSqlSessionFactory().openSession(true);
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		if (factory == null) {
			factory = getSqlSessionFactoryBuilder().build(getReader());
		}
		return factory;
	}

	public static SqlSessionFactoryBuilder getSqlSessionFactoryBuilder() {
		if (builder == null) {
			builder = new SqlSessionFactoryBuilder();
		}
		return builder;
	}


	public static <T> T getMapper(Class<T> type) {
		return getSqlSessionFactory().openSession().getMapper(type);
	}
}
